package mysql

import (
	"context"
	"errors"

	"github.com/myblogs/models"
)

var (
	ErrorArticleExits    = errors.New("文章已经存在")
	ErrorArticleNotExits = errors.New("文章不存在")
)

type ArticleDaoInterface interface {
	CreatedArtical(c context.Context, req *models.Article) (article *models.Article, err error)
	GetArticleByID(c context.Context, id int64) (*models.Article, error)
	GetArticleByUserID(c context.Context, id int64) (*[]models.Article, error)
	DeleteArticle(c context.Context, id int64) error
	UpdateArticle(c context.Context, id int64, req *models.Article) error
	GetAllArticles(c context.Context) (*[]models.Article, error)
}
type ArticleDaoImpl struct {
}

func NewArticleDaoImpl() *ArticleDaoImpl {
	return &ArticleDaoImpl{}
}
func (a *ArticleDaoImpl) CreatedArtical(c context.Context, req *models.Article) (article *models.Article, err error) {
	err = DB.Model(&models.Article{}).Create(&req).Error
	if err != nil {
		return nil, err
	}
	return req, nil
}
func (a *ArticleDaoImpl) GetArticleByID(c context.Context, id int64) (*models.Article, error) {
	var article models.Article
	result := DB.Where("article_id = ?", id).First(&article)
	if result.Error != nil {
		return nil, result.Error
	}
	if result.RowsAffected == 0 {
		return nil, ErrorArticleNotExits
	}
	return &article, nil
}
func (a *ArticleDaoImpl) GetArticleByUserID(c context.Context, id int64) (*[]models.Article, error) {
	// var articles []models.Article
	var user models.User
	result := DB.Preload("Articles").Where("user_id = ?", id).Find(&user)
	if result.Error != nil {
		return nil, result.Error
	}
	if result.RowsAffected == 0 {
		return nil, ErrorArticleNotExits
	}
	return &user.Articles, nil
}
func (a *ArticleDaoImpl) DeleteArticle(c context.Context, id int64) error {
	return DB.Model(&models.Article{}).Where("id = ?", id).Delete(&models.Article{}).Error
}
func (a *ArticleDaoImpl) UpdateArticle(c context.Context, id int64, req *models.Article) error {
	return DB.Model(&models.Article{}).Where("id = ?", id).Updates(&req).Error
}
func (a *ArticleDaoImpl) GetAllArticles(c context.Context) (*[]models.Article, error) {
	var articles []models.Article
	result := DB.Find(&articles)
	if result.Error != nil {
		return nil, result.Error
	}
	if result.RowsAffected == 0 {
		return nil, ErrorArticleNotExits
	}
	return &articles, nil
}
